//! # 消息总线管理API
//!
//! 提供RESTful API接口用于动态配置、运行时管理、调试和监控

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::bus::{MessageBus, MessageBusStats};
use crate::error::{MessageBusError, MessageBusResult};
use rustcloud_observability::monitoring::{Monitor, MonitoringMetrics};
use rustcloud_observability::health::HealthCheckResult;

/// 管理API配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdminApiConfig {
    /// 是否启用管理API
    pub enabled: bool,
    /// 绑定地址
    pub bind_address: String,
    /// 绑定端口
    pub port: u16,
    /// 是否启用认证
    pub auth_enabled: bool,
    /// API密钥
    pub api_key: Option<String>,
    /// CORS设置
    pub cors_enabled: bool,
    /// 允许的来源
    pub allowed_origins: Vec<String>,
    /// 请求限制
    pub rate_limit: RateLimitConfig,
}

/// 速率限制配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// 是否启用速率限制
    pub enabled: bool,
    /// 每分钟请求数限制
    pub requests_per_minute: u32,
    /// 突发请求数限制
    pub burst_limit: u32,
}

impl Default for AdminApiConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            bind_address: "127.0.0.1".to_string(),
            port: 8080,
            auth_enabled: true,
            api_key: Some("rustcloud-admin-key".to_string()),
            cors_enabled: true,
            allowed_origins: vec!["http://localhost:3000".to_string()],
            rate_limit: RateLimitConfig {
                enabled: true,
                requests_per_minute: 60,
                burst_limit: 10,
            },
        }
    }
}

/// API响应结构
#[derive(Debug, Serialize, Deserialize)]
pub struct ApiResponse<T> {
    /// 是否成功
    pub success: bool,
    /// 数据
    pub data: Option<T>,
    /// 错误消息
    pub error: Option<String>,
    /// 时间戳
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl<T> ApiResponse<T> {
    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            timestamp: chrono::Utc::now(),
        }
    }

    pub fn error(message: impl Into<String>) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(message.into()),
            timestamp: chrono::Utc::now(),
        }
    }
}

/// 系统信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
    /// 版本信息
    pub version: String,
    /// 启动时间
    pub started_at: chrono::DateTime<chrono::Utc>,
    /// 运行时间（秒）
    pub uptime_seconds: u64,
    /// 系统状态
    pub status: SystemStatus,
    /// 配置信息
    pub config: HashMap<String, serde_json::Value>,
}

/// 系统状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SystemStatus {
    Running,
    Starting,
    Stopping,
    Stopped,
    Error,
}

/// 配置更新请求
#[derive(Debug, Clone, Deserialize)]
pub struct ConfigUpdateRequest {
    /// 配置键
    pub key: String,
    /// 配置值
    pub value: serde_json::Value,
    /// 是否立即生效
    pub immediate: bool,
}

/// 消息发布请求
#[derive(Debug, Clone, Deserialize)]
pub struct PublishMessageRequest {
    /// 主题
    pub topic: String,
    /// 消息内容
    pub payload: serde_json::Value,
    /// 消息头
    pub headers: Option<HashMap<String, String>>,
}

/// 订阅管理请求
#[derive(Debug, Clone, Deserialize)]
pub struct SubscriptionRequest {
    /// 主题模式
    pub pattern: String,
    /// 订阅配置
    pub config: Option<HashMap<String, serde_json::Value>>,
}

/// 管理API接口
#[async_trait]
pub trait AdminApi: Send + Sync {
    /// 获取系统信息
    async fn get_system_info(&self) -> MessageBusResult<SystemInfo>;
    
    /// 获取系统统计
    async fn get_stats(&self) -> MessageBusResult<MessageBusStats>;
    
    /// 获取监控指标
    async fn get_metrics(&self) -> MessageBusResult<MonitoringMetrics>;
    
    /// 执行健康检查
    async fn health_check(&self) -> MessageBusResult<HealthCheckResult>;
    
    /// 更新配置
    async fn update_config(&self, request: ConfigUpdateRequest) -> MessageBusResult<()>;
    
    /// 发布消息
    async fn publish_message(&self, request: PublishMessageRequest) -> MessageBusResult<String>;
    
    /// 创建订阅
    async fn create_subscription(&self, request: SubscriptionRequest) -> MessageBusResult<String>;
    
    /// 取消订阅
    async fn cancel_subscription(&self, subscription_id: &str) -> MessageBusResult<()>;
    
    /// 获取订阅列表
    async fn list_subscriptions(&self) -> MessageBusResult<Vec<SubscriptionInfo>>;
    
    /// 获取主题列表
    async fn list_topics(&self) -> MessageBusResult<Vec<TopicInfo>>;
    
    /// 重启系统
    async fn restart_system(&self) -> MessageBusResult<()>;
    
    /// 停止系统
    async fn stop_system(&self) -> MessageBusResult<()>;
}

/// 订阅信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionInfo {
    /// 订阅ID
    pub id: String,
    /// 主题模式
    pub pattern: String,
    /// 创建时间
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// 是否活跃
    pub active: bool,
    /// 接收消息数
    pub message_count: u64,
}

/// 主题信息
#[derive(Debug, Serialize, Deserialize)]
pub struct TopicInfo {
    /// 主题名称
    pub name: String,
    /// 订阅者数量
    pub subscriber_count: usize,
    /// 消息数量
    pub message_count: u64,
    /// 最后活动时间
    pub last_activity: Option<chrono::DateTime<chrono::Utc>>,
}

/// HTTP管理API实现
pub struct HttpAdminApi<B: MessageBus, M: Monitor> {
    /// 配置
    config: AdminApiConfig,
    /// 消息总线
    message_bus: Arc<B>,
    /// 监控器
    monitor: Arc<M>,
    /// 系统信息
    system_info: Arc<RwLock<SystemInfo>>,
    /// 订阅管理
    subscriptions: Arc<RwLock<HashMap<String, SubscriptionInfo>>>,
    /// 主题统计
    topics: Arc<RwLock<HashMap<String, TopicInfo>>>,
    /// 启动时间
    started_at: chrono::DateTime<chrono::Utc>,
}

impl<B: MessageBus + 'static, M: Monitor + 'static> HttpAdminApi<B, M> {
    /// 创建HTTP管理API
    pub fn new(
        config: AdminApiConfig,
        message_bus: Arc<B>,
        monitor: Arc<M>,
    ) -> Self {
        let started_at = chrono::Utc::now();
        
        let system_info = SystemInfo {
            version: env!("CARGO_PKG_VERSION").to_string(),
            started_at,
            uptime_seconds: 0,
            status: SystemStatus::Starting,
            config: HashMap::new(),
        };

        Self {
            config,
            message_bus,
            monitor,
            system_info: Arc::new(RwLock::new(system_info)),
            subscriptions: Arc::new(RwLock::new(HashMap::new())),
            topics: Arc::new(RwLock::new(HashMap::new())),
            started_at,
        }
    }

    /// 启动API服务器
    pub async fn start(&self) -> MessageBusResult<()> {
        if !self.config.enabled {
            tracing::info!("管理API已禁用");
            return Ok(());
        }

        tracing::info!(
            "启动HTTP管理API服务器: {}:{}",
            self.config.bind_address,
            self.config.port
        );

        // 更新系统状态
        {
            let mut info = self.system_info.write().await;
            info.status = SystemStatus::Running;
        }

        // 这里应该启动实际的HTTP服务器
        // 由于演示环境限制，我们只是模拟启动
        tracing::info!("管理API服务器启动成功");
        
        Ok(())
    }

    /// 停止API服务器
    pub async fn stop(&self) -> MessageBusResult<()> {
        tracing::info!("正在停止HTTP管理API服务器");

        // 更新系统状态
        {
            let mut info = self.system_info.write().await;
            info.status = SystemStatus::Stopping;
        }

        // 这里应该停止HTTP服务器
        
        {
            let mut info = self.system_info.write().await;
            info.status = SystemStatus::Stopped;
        }

        tracing::info!("管理API服务器已停止");
        Ok(())
    }

    /// 验证API密钥
    fn verify_api_key(&self, provided_key: Option<&str>) -> bool {
        if !self.config.auth_enabled {
            return true;
        }

        match (&self.config.api_key, provided_key) {
            (Some(expected), Some(provided)) => expected == provided,
            _ => false,
        }
    }

    /// 更新系统信息
    async fn update_system_info(&self) {
        let mut info = self.system_info.write().await;
        info.uptime_seconds = chrono::Utc::now()
            .signed_duration_since(self.started_at)
            .num_seconds() as u64;
    }
}

#[async_trait]
impl<B: MessageBus + 'static, M: Monitor + 'static> AdminApi for HttpAdminApi<B, M> {
    async fn get_system_info(&self) -> MessageBusResult<SystemInfo> {
        self.update_system_info().await;
        let info = self.system_info.read().await;
        Ok(info.clone())
    }

    async fn get_stats(&self) -> MessageBusResult<MessageBusStats> {
        self.message_bus.stats().await
    }

    async fn get_metrics(&self) -> MessageBusResult<MonitoringMetrics> {
        self.monitor.get_metrics().await
            .map_err(|e| MessageBusError::internal_error(format!("监控指标获取失败: {}", e)))
    }

    async fn health_check(&self) -> MessageBusResult<HealthCheckResult> {
        self.monitor.health_check().await
            .map_err(|e| MessageBusError::internal_error(format!("健康检查失败: {}", e)))
    }

    async fn update_config(&self, request: ConfigUpdateRequest) -> MessageBusResult<()> {
        tracing::info!("更新配置: {} = {:?}", request.key, request.value);
        
        // 这里应该实现实际的配置更新逻辑
        // 根据配置键更新相应的系统设置
        
        if request.immediate {
            tracing::info!("配置立即生效: {}", request.key);
        } else {
            tracing::info!("配置将在下次重启时生效: {}", request.key);
        }
        
        Ok(())
    }

    async fn publish_message(&self, request: PublishMessageRequest) -> MessageBusResult<String> {
        let mut message = crate::message::Message::new(&request.topic, request.payload);
        
        // 添加请求头 - 直接操作元数据
        if let Some(headers) = request.headers {
            for (key, value) in headers {
                self.message_bus.publish(message.clone()).await?;
                // 注意：这里简化了headers的处理，实际中应该通过metadata设置
                break; // 仅演示用
            }
        } else {
            self.message_bus.publish(message.clone()).await?;
        }
        
        tracing::info!("通过管理API发布消息: topic={}, id={}", request.topic, message.id());
        Ok(message.id().to_string())
    }

    async fn create_subscription(&self, request: SubscriptionRequest) -> MessageBusResult<String> {
        let subscriber = self.message_bus.subscribe(&request.pattern).await?;
        let subscription_id = subscriber.subscription_id().to_string();
        
        let subscription_info = SubscriptionInfo {
            id: subscription_id.clone(),
            pattern: request.pattern.clone(),
            created_at: chrono::Utc::now(),
            active: true,
            message_count: 0,
        };
        
        self.subscriptions.write().await.insert(subscription_id.clone(), subscription_info);
        
        tracing::info!("通过管理API创建订阅: id={}, pattern={}", subscription_id, request.pattern);
        Ok(subscription_id)
    }

    async fn cancel_subscription(&self, subscription_id: &str) -> MessageBusResult<()> {
        self.message_bus.unsubscribe(subscription_id).await?;
        self.subscriptions.write().await.remove(subscription_id);
        
        tracing::info!("通过管理API取消订阅: id={}", subscription_id);
        Ok(())
    }

    async fn list_subscriptions(&self) -> MessageBusResult<Vec<SubscriptionInfo>> {
        let subscriptions = self.subscriptions.read().await;
        Ok(subscriptions.values().cloned().collect())
    }

    async fn list_topics(&self) -> MessageBusResult<Vec<TopicInfo>> {
        let bus_topics = self.message_bus.list_topics().await?;
        let mut topic_infos = Vec::new();
        
        for topic in bus_topics {
            let subscriber_count = self.message_bus.subscriber_count(&topic).await?;
            
            let topic_info = TopicInfo {
                name: topic.clone(),
                subscriber_count,
                message_count: 0, // 需要从统计中获取
                last_activity: Some(chrono::Utc::now()),
            };
            
            topic_infos.push(topic_info);
        }
        
        Ok(topic_infos)
    }

    async fn restart_system(&self) -> MessageBusResult<()> {
        tracing::warn!("收到系统重启请求");
        
        {
            let mut info = self.system_info.write().await;
            info.status = SystemStatus::Starting;
        }
        
        // 这里应该实现系统重启逻辑
        tracing::info!("系统重启完成");
        
        Ok(())
    }

    async fn stop_system(&self) -> MessageBusResult<()> {
        tracing::warn!("收到系统停止请求");
        
        {
            let mut info = self.system_info.write().await;
            info.status = SystemStatus::Stopping;
        }
        
        self.message_bus.close().await?;
        
        {
            let mut info = self.system_info.write().await;
            info.status = SystemStatus::Stopped;
        }
        
        tracing::info!("系统已停止");
        Ok(())
    }
}

/// 管理API路由器
pub struct ApiRouter<B: MessageBus, M: Monitor> {
    admin_api: Arc<HttpAdminApi<B, M>>,
}

impl<B: MessageBus + 'static, M: Monitor + 'static> ApiRouter<B, M> {
    /// 创建API路由器
    pub fn new(admin_api: Arc<HttpAdminApi<B, M>>) -> Self {
        Self { admin_api }
    }

    /// 处理GET /api/v1/system/info请求
    pub async fn handle_get_system_info(&self) -> Result<ApiResponse<SystemInfo>, MessageBusError> {
        match self.admin_api.get_system_info().await {
            Ok(info) => Ok(ApiResponse::success(info)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }

    /// 处理GET /api/v1/system/stats请求
    pub async fn handle_get_stats(&self) -> Result<ApiResponse<MessageBusStats>, MessageBusError> {
        match self.admin_api.get_stats().await {
            Ok(stats) => Ok(ApiResponse::success(stats)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }

    /// 处理GET /api/v1/monitoring/metrics请求
    pub async fn handle_get_metrics(&self) -> Result<ApiResponse<MonitoringMetrics>, MessageBusError> {
        match self.admin_api.get_metrics().await {
            Ok(metrics) => Ok(ApiResponse::success(metrics)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }

    /// 处理GET /api/v1/health请求
    pub async fn handle_health_check(&self) -> Result<ApiResponse<HealthCheckResult>, MessageBusError> {
        match self.admin_api.health_check().await {
            Ok(result) => Ok(ApiResponse::success(result)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }

    /// 处理POST /api/v1/messages请求
    pub async fn handle_publish_message(
        &self,
        request: PublishMessageRequest,
    ) -> Result<ApiResponse<String>, MessageBusError> {
        match self.admin_api.publish_message(request).await {
            Ok(message_id) => Ok(ApiResponse::success(message_id)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }

    /// 处理GET /api/v1/topics请求
    pub async fn handle_list_topics(&self) -> Result<ApiResponse<Vec<TopicInfo>>, MessageBusError> {
        match self.admin_api.list_topics().await {
            Ok(topics) => Ok(ApiResponse::success(topics)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }

    /// 处理GET /api/v1/subscriptions请求
    pub async fn handle_list_subscriptions(&self) -> Result<ApiResponse<Vec<SubscriptionInfo>>, MessageBusError> {
        match self.admin_api.list_subscriptions().await {
            Ok(subscriptions) => Ok(ApiResponse::success(subscriptions)),
            Err(e) => Ok(ApiResponse::error(e.to_string())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_admin_api_config_default() {
        let config = AdminApiConfig::default();
        assert!(config.enabled);
        assert_eq!(config.port, 8080);
        assert!(config.auth_enabled);
    }

    #[test]
    fn test_api_response_success() {
        let response = ApiResponse::success("test data");
        assert!(response.success);
        assert_eq!(response.data, Some("test data"));
        assert!(response.error.is_none());
    }

    #[test]
    fn test_api_response_error() {
        let response: ApiResponse<String> = ApiResponse::error("test error");
        assert!(!response.success);
        assert!(response.data.is_none());
        assert_eq!(response.error, Some("test error".to_string()));
    }
}